package com.ityu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ityu.exception.InsertSameException;
import com.ityu.exception.UnableDeleteException;
import com.ityu.mapper.ClazzMapper;
import com.ityu.pojo.Clazz;
import com.ityu.pojo.pagePojo.ClazzPage;
import com.ityu.pojo.result.PageResult;
import com.ityu.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> pageFindClazz(ClazzPage clazzPage) {
        PageHelper.startPage(clazzPage.getPage(),clazzPage.getPageSize());
        List<Clazz> clazzes = clazzMapper.pageFindClazz(clazzPage);
        for (Clazz clazz : clazzes) {
            if (LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("已开班");
            }
        }
        Page<Clazz> page = (Page<Clazz>) clazzes;
        return new PageResult<Clazz>( page.getTotal(),page.getResult());
    }

    @Override
    public void deleteClass(Integer id) {
        log.info("-----ClazzService-----删除班级,参数为{}", id);
        if (clazzMapper.countStudent(id) == 0) {
            clazzMapper.deleteClass(id);
        } else {
            log.error("删除有学生的班级{}", id);
            throw new UnableDeleteException("删除班级失败，该班级下有学生");
        }
    }

    @Override
    public void addClass(Clazz clazz) {
        log.info("-----ClazzService-----添加班级,参数为{}", clazz);
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        try {
            clazzMapper.addClass(clazz);
        } catch (DuplicateKeyException e) {
            log.error("插入重复班级名称{}" ,clazz.getName());
            throw new InsertSameException("班级数据不合法或重复，请重试！");
        }
    }

    @Override
    public Clazz getClassById(Integer id) {
        log.info("-----ClazzService-----根据id查询班级,参数为{}", id);
        return clazzMapper.getClassById(id);
    }

    @Override
    public void updateClass(Clazz clazz) {
        log.info("-----ClazzService-----更新班级,参数为{}", clazz);
        clazz.setUpdateTime(LocalDateTime.now());
        try {
            clazzMapper.updateClass(clazz);
        } catch (DuplicateKeyException e) {
            log.error("修改重复班级名称{}" ,clazz.getName());
            throw new InsertSameException("班级数据不合法或重复，请重试！");
        }
    }

    @Override
    public List<Clazz> listClass() {
        log.info("-----ClazzService-----查询所有班级");
        return clazzMapper.listClass();
    }
}
